//
//  JKEmoticonAttributedString.swift
//  JKWeiBo
//
//  Created by 王冲 on 2018/2/10.
//  Copyright © 2018年 希爱欧科技有限公司. All rights reserved.
//

import UIKit

class JKEmoticonAttributedString: NSObject {

    // MARK: 从后取值
    func backwards(str: String,font:CGFloat) -> NSAttributedString? {
        
        // 生成完整的属性字符串
        let strM = NSMutableAttributedString(string: str)
        do{
            // 1.创建规则
            let pattern = "\\[.*?\\]"
            
            // 2.创建正则表达式对象
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            // 3.开始匹配
            let res = regex.matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))
            // 4取出结果
            /*
             // 有问题: 正向替换会修改字符串的长度, 会影响后面字符串的range
             for checkingRes in res
             {
             // 1.拿到匹配到的表情字符串
             let tempStr = (str as NSString).substringWithRange(checkingRes.range)
             print(tempStr)
             // 2.根据表情字符串查找对应的表情模型
             if let emoticon = emoticonWithStr(tempStr)
             {
             // 3.根据表情模型生成属性字符串
             let attrStr = EmoticonTextAttachment.imageText(emoticon, font: UIFont.systemFontOfSize(18))
             // 4.添加属性字符串
             strM.replaceCharactersInRange(checkingRes.range, withAttributedString: attrStr)
             }
             
             }
             */
            var count = res.count
            while count > 0
            {
                // 0.从后面开始取
                count = count-1
                let checkingRes = res[count]
                
                // 1.拿到匹配到的表情字符串
                let tempStr = (str as NSString).substring(with: checkingRes.range)
                //                print(tempStr)
                // 2.根据表情字符串查找对应的表情模型
                if let emoticon = emoticonWithStr(str: tempStr)
                {
                    print(emoticon.chs!)
                    // 3.根据表情模型生成属性字符串
                    let attrStr = JKEmoticonTextAttachment.imageText(emoticon: emoticon, font: UIFont.systemFont(ofSize: font))
                    // 4.添加属性字符串
                    strM.replaceCharacters(in: checkingRes.range, with: attrStr)
                }
            }
            
            // 拿到替换之后的属性字符串
            return strM
        }catch
        {
            print(error)
        }
        return nil
    }
    
    
    /**
     根据表情文字找到对应的表情模型
     
     :param: str 表情文字
     
     :returns: 表情模型
     */
    func emoticonWithStr(str: String) -> JKEmoticon?
    {
        var emoticon: JKEmoticon?
        for package in JKEmoticonPackage.packageslist
        {
            emoticon = package.emoticons?.filter({ (e) -> Bool in
                return e.chs == str
            }).last
            
            if emoticon != nil{
                break
            }
        }
        return emoticon
    }
    
}
